#!/bin/bash
# 商业转载请联系作者获得授权，非商业转载请注明出处。
# 协议(License): CC BY-NC-SA 4.0
# 作者(Author): 寒雨馨
# 链接(URL): /archives/java-duo-ban-ben-an-zhuang-guan-li-jiao-ben

set -e  # 出错立即退出

# 默认安装目录
DEFAULT_INSTALL_DIR="/opt/java"
CONFIG_DIR="$HOME/.java-installer"
INSTALL_CONFIG="$CONFIG_DIR/install_path.conf"
CONFIG_FILE="/etc/profile.d/java.sh"

# 可选 Java 版本
declare -a JAVA_VERSIONS=("8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23" "24")

# 支持的发行版
declare -A JDK_DISTROS=(
    [1]="Adoptium"
    [2]="Azul Zulu"
    [3]="Amazon Corretto"
    [4]="BellSoft Liberica"
    [5]="IBM Semeru"
)

# CPU 架构和系统类型
ARCH=$(uname -m)
case "$ARCH" in
    x86_64) MACHINE_TYPE="x64" ;;
    aarch64) MACHINE_TYPE="aarch64" ;;
    *) echo "❌ 不支持的架构: $ARCH"; exit 1 ;;
esac

OS_NAME=$(uname -s)
case "$OS_NAME" in
    Linux) OS_TYPE="linux" ;;
    Darwin) OS_TYPE="mac" ;;
    *) echo "❌ 不支持的操作系统: $OS_NAME"; exit 1 ;;
esac

# 创建配置目录
mkdir -p "$CONFIG_DIR"

# 获取安装路径
get_install_dir() {
    if [ -f "$INSTALL_CONFIG" ]; then
        INSTALL_DIR=$(cat "$INSTALL_CONFIG")
        echo "✅ 使用上次保存的安装路径: $INSTALL_DIR"
    else
        read -p "请输入 Java 安装目录 (默认: $DEFAULT_INSTALL_DIR): " USER_INSTALL_DIR
        INSTALL_DIR="${USER_INSTALL_DIR:-$DEFAULT_INSTALL_DIR}"
        mkdir -p "$INSTALL_DIR"
        echo "$INSTALL_DIR" > "$INSTALL_CONFIG"
        echo "✅ 安装路径已保存为: $INSTALL_DIR"
    fi
}

# 获取已安装版本
get_installed_versions() {
    if [ -d "$INSTALL_DIR" ]; then
        INSTALLED=($(ls -1 "$INSTALL_DIR" | grep -E '^[0-9]+$'))
    else
        INSTALLED=()
    fi
}

# 显示主菜单
show_main_menu() {
    clear
    echo "=== Java 多版本安装与切换工具 ==="
    echo "安装路径: $INSTALL_DIR"
    echo "----------------------------------"
    echo "1) 安装新的 Java 版本"
    echo "2) 查看已安装版本"
    echo "3) 切换当前 Java 版本"
    echo "4) 卸载某个版本"
    echo "5) 更改安装路径"
    echo "0) 退出程序"
    echo "----------------------------------"
    read -p "请选择操作 (0-5): " choice

    if [[ "$choice" =~ ^[0-5]$ ]]; then
        handle_choice "$choice"
    else
        echo "❌ 无效选项，请输入 0~5 的数字。"
        sleep 1
        show_main_menu
    fi
}

# 显示安装菜单
show_install_menu() {
    echo "请选择要安装的发行版："
    for key in "${!JDK_DISTROS[@]}"; do
        echo "$key) ${JDK_DISTROS[$key]}"
    done
    read -p "请输入编号: " distro_choice
    if ! [[ "$distro_choice" =~ ^[1-5]$ ]]; then
        echo "❌ 无效选择！"
        sleep 1
        return
    fi
    JDK_SELECTED=${JDK_DISTROS[$distro_choice]}

    echo "可选 Java 版本："
    for i in "${!JAVA_VERSIONS[@]}"; do
        echo "$((i+1))) Java ${JAVA_VERSIONS[$i]}"
    done
    echo "0) 返回上一级"
    read -p "请输入编号 (0-${#JAVA_VERSIONS[@]}): " choice

    if [[ "$choice" == "0" ]]; then return; fi
    if (( choice >= 1 && choice <= ${#JAVA_VERSIONS[@]} )); then
        VERSION=${JAVA_VERSIONS[$((choice-1))]}
        install_java "$VERSION"
    else
        echo "❌ 无效输入。"
    fi
}

# 生成下载链接
generate_download_url() {
    local version="$1"
    case "$JDK_SELECTED" in
        "Adoptium")
            URL="https://github.com/adoptium/temurin${version}-binaries/releases/latest/download/OpenJDK${version}U-jdk_${MACHINE_TYPE}_${OS_TYPE}_hotspot.tar.gz"
            ;;
        "Azul Zulu")
            URL="https://cdn.azul.com/zulu/bin/zulu${version}-ca-jdk${version}-${OS_TYPE}_${MACHINE_TYPE}.tar.gz"
            ;;
        "Amazon Corretto")
            URL="https://corretto.aws/downloads/latest/amazon-corretto-${version}-x64-linux-jdk.tar.gz"
            ;;
        "BellSoft Liberica")
            URL="https://download.bell-sw.com/java/${version}/bellsoft-jdk${version}+${version}-linux-${MACHINE_TYPE}.tar.gz"
            ;;
        "IBM Semeru")
            URL="https://github.com/ibmruntimes/semeru${version}-binaries/releases/download/jdk-${version}+${version}/ibm-semeru-open-jdk_${OS_TYPE}_${MACHINE_TYPE}_jdk_${version}_${version}.tar.gz"
            ;;
        *)
            echo "❌ 不支持的发行版"
            exit 1
            ;;
    esac
}

# 安装指定版本的 Java
install_java() {
    local version="$1"
    echo "⏳ 正在安装 Java $version ($JDK_SELECTED)..."
    generate_download_url "$version"

    # 创建安装目录
    mkdir -p "$INSTALL_DIR/$version"

    echo "📥 正在下载 JDK... $URL"
    wget -O "/tmp/java-$version.tar.gz" "$URL" || { echo "❌ 下载失败，请检查网络或链接是否有效。"; sleep 2; return; }

    echo "📦 正在解压到 $INSTALL_DIR/$version ..."
    tar -xzf "/tmp/java-$version.tar.gz" -C "$INSTALL_DIR/$version" --strip-components=1
    rm "/tmp/java-$version.tar.gz"

    echo "✅ Java $version ($JDK_SELECTED) 已安装到 $INSTALL_DIR/$version"
    sleep 1
}

# 显示已安装版本
list_installed_versions() {
    get_installed_versions
    echo "📚 已安装的 Java 版本："
    if [ ${#INSTALLED[@]} -eq 0 ]; then
        echo "❌ 无版本安装"
    else
        for ver in "${INSTALLED[@]}"; do
            echo "- Java $ver"
        done
    fi
    read -p "按回车继续..."
}

# 切换 Java 版本
switch_java_version() {
    get_installed_versions
    if [ ${#INSTALLED[@]} -eq 0 ]; then
        echo "❌ 没有已安装的 Java 版本。"
        sleep 1
        return
    fi

    echo "请选择要启用的 Java 版本："
    for i in "${!INSTALLED[@]}"; do
        echo "$((i+1))) Java ${INSTALLED[$i]}"
    done
    echo "0) 返回上一级"
    read -p "请输入编号: " choice

    if [[ "$choice" == "0" ]]; then return; fi
    if (( choice >= 1 && choice <= ${#INSTALLED[@]} )); then
        NEW_VERSION=${INSTALLED[$((choice-1))]}
        echo "export JAVA_HOME=$INSTALL_DIR/$NEW_VERSION" | sudo tee "$CONFIG_FILE" > /dev/null
        echo "export PATH=\$JAVA_HOME/bin:\$PATH" | sudo tee -a "$CONFIG_FILE" > /dev/null
        source "$CONFIG_FILE"
        echo "✅ 已切换为 Java $NEW_VERSION"
        java -version
    else
        echo "❌ 无效输入。"
    fi
    sleep 2
}

# 卸载某个版本
uninstall_java_version() {
    get_installed_versions
    if [ ${#INSTALLED[@]} -eq 0 ]; then
        echo "❌ 没有可卸载的 Java 版本。"
        sleep 1
        return
    fi

    echo "请选择要卸载的 Java 版本："
    for i in "${!INSTALLED[@]}"; do
        echo "$((i+1))) Java ${INSTALLED[$i]}"
    done
    echo "0) 返回上一级"
    read -p "请输入编号: " choice

    if [[ "$choice" == "0" ]]; then return; fi
    if (( choice >= 1 && choice <= ${#INSTALLED[@]} )); then
        UN_VERSION=${INSTALLED[$((choice-1))]}
        sudo rm -rf "$INSTALL_DIR/$UN_VERSION"
        echo "✅ Java $UN_VERSION 已卸载。"
    else
        echo "❌ 无效输入。"
    fi
    sleep 2
}

# 更改安装路径
change_install_dir() {
    read -p "请输入新的 Java 安装目录 (当前: $INSTALL_DIR): " NEW_INSTALL_DIR
    if [ -n "$NEW_INSTALL_DIR" ]; then
        INSTALL_DIR="$NEW_INSTALL_DIR"
        mkdir -p "$INSTALL_DIR"
        echo "$INSTALL_DIR" > "$INSTALL_CONFIG"
        echo "✅ 安装路径已更改为: $INSTALL_DIR"
    fi
    sleep 1
}

# 主处理逻辑
handle_choice() {
    case "$1" in
        1) show_install_menu ;;
        2) list_installed_versions ;;
        3) switch_java_version ;;
        4) uninstall_java_version ;;
        5) change_install_dir ;;
        0) echo "👋 退出程序。"; exit 0 ;;
        *) echo "❌ 无效选项"; sleep 1 ;;
    esac
}

# 启动脚本
main() {
    get_install_dir
    while true; do
        show_main_menu
    done
}

main